<template>
  <view>
    <u-navbar
      :is-back="false"
      :background="navbarBackground"
      :height="navigationHeight"
    >
      <view class="am-flex-rc-center navbar-slot-wrap">
        <image :src="NAV_BAR_TITLE" class="navbar-title-img"></image>
      </view>
      <view
        class="am-flex-row-center navbar-slot-wrap"
        :style="{ paddingRight: `${menuPlaceWidth}px` }"
      >
      </view>
    </u-navbar>
    <view class="aside" :style="{ top: `${navBarHeight}px` }">
      <scroll-view
        scroll-y="true"
        class="aside-scroll"
        :scroll-into-view="curIntoId"
      >
        <view class="aside-content">
          <view
            class="aside-list am-flex-rc-center"
            :class="{ active: curSelectIndex === index }"
            v-for="(item, index) in categoryList"
            :key="item.cid"
            @click="asideItem(index, item)"
            :id="'asideList_' + item.cid"
          >
            <view
              class="line-active"
              :class="{ active: curSelectIndex === index }"
            ></view>
            <text class="am-text-eill">{{ item.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="products-wrap">
      <view
        class="category-product-section"
        v-for="(item, index) in dataList"
        :key="item.cid"
      >
        <view class="product-section-header am-flex-row-center">{{
          item.name
        }}</view>
        <view
          style="flex-wrap: wrap"
          class="product-section-content am-flex-row-center"
        >
          <view
            @click="goSecondCategory(index, indexC)"
            v-for="(itemC, indexC) in item.categors"
            :key="indexC"
            class="product-section-second am-flex-col-center"
          >
            <image
              class="product-section-second-img"
              :src="itemC.logoImg"
              mode="scaleToFill"
            />
            <view class="category-name am-text-eill">{{ itemC.name }}</view>
          </view>
        </view>
      </view>
    </view>
    <co-empty
      paddingTop="300rpx"
      :show="!getLoading && dataList.length === 0"
    ></co-empty>
    <purchaseGoods
      :showModal="showPay"
      :detail="goodsData"
      @close="onclose"
      @submit="submit"
      :type="type"
    ></purchaseGoods>
  </view>
</template>

<script>
import { apiCategoryGoods } from '@/api/goods'
import purchaseGoods from '@/components/purchase-goods/purchase-goods'
import tabbarPage from '@/mixins/tabbarPage'
import { NAV_BAR_TITLE } from '@/types/navbar.js'
import { appOnLaunch } from '@/utils/appGlobalLifeCycle'
import { navBarHeight, navigationHeight } from '@/utils/systemInfo.js'
import throttle from 'lodash-es/throttle'
import RetailPriceSign from './components/retail-price-sign.vue'
const windowHeight = uni.getSystemInfoSync().windowHeight

/**
 * 采用懒更新方案，只有当供应商变了，并且进入当前页面，才会更新数据
 * */
export default {
  data() {
    return {
      NAV_BAR_TITLE,
      navbarBackground: {
        background: '#FFFFFF'
      },
      navigationHeight,
      navBarHeight,
      categoryList: [],
      dataList: [],
      curSelectIndex: 0,
      curIntoId: '',
      shouldUpdate: true, // 是否应该更新
      getLoading: false, // 是否正在刷新列表
      showPay: false,
      type: 1,
      goodsData: {},
      currentId: 0,
      firstId: ''
    }
  },
  components: {
    RetailPriceSign,
    purchaseGoods
  },
  created() {
    // uni.getStorage({
    //   key: 'currentId',
    //   success: (res) => {
    //     console.log(res.data) // 输出存储的参数
    //     this.currentId = res.data.currentId
    //   }
    // })
  },
  onLoad() {
    // this.getProductsList()
    // uni.$on(UPDATE_CATEGORY_LIST, this.updateCategroy);
  },
  onUnload() {
    // uni.$off(UPDATE_CATEGORY_LIST, this.updateCategroy);
  },
  onShow() {
    if (!this.$store.getters.isLogin) {
      appOnLaunch()
      return
    }
    if (this.shouldUpdate && !this.getLoading) {
      this.unlockInit()
    }
  },
  mixins: [tabbarPage],
  computed: {},
  onPageScroll(e) {
    this.pageScrollHanlde(e)
  },
  methods: {
    onclose(show) {
      this.showPay = show
      uni.showTabBar()
    },
    submit(data) {
      uni.showTabBar()
      if (this.type == 1) {
        this.apiAddCart(data)
      } else {
        this.$u.route('pages/place-order/submit-order', {
          val: JSON.stringify(data.val)
        })
      }
      this.showPay = false
    },
    goSecondCategory(firstIndex, index) {
      this.$u.route('/pages/category/secondCategory', {
        firstIndex: firstIndex,
        index: index
      })
    },
    // 启用规格窗口
    addCart(type, val, num) {
      if (num) return
      this.goodsData = val
      this.showPay = true
      uni.hideTabBar()
      this.type = type
    },
    dataInit() {
      this.dataList = []
      this.categoryList = []
      this.curSelectIndex = 0
      this.curIntoId = ''
    },
    unlockInit() {
      this.dataInit()
      this.getProductsList()
    },
    pageScrollHanlde: throttle(
      function (e) {
        let topValArray = [...this.topValArray].reverse()
        let topValLen = topValArray.length
        for (let i = 0; i < topValLen; i++) {
          // 补偿50像素
          if (e.scrollTop + navBarHeight + 50 > topValArray[i]) {
            let zhenXuIndex = topValLen - i - 1
            this.curSelectIndex = zhenXuIndex
            /**
             * 补偿一下不要让它滚到最上边
             * */
            if (zhenXuIndex > 2) {
              let curCid = this.categoryList[zhenXuIndex - 2].cid
              this.curIntoId = `asideList_${curCid}`
            } else {
              let curCid = this.categoryList[0].cid
              this.curIntoId = `asideList_${curCid}`
            }
            break
          }
        }
      },
      500,
      { leading: false, trailing: true }
    ),
    getProductsList() {
      if (this.getLoading) return
      this.getLoading = true
      uni.showLoading({
        mask: true
      })
      apiCategoryGoods()
        .then((res) => {
          let { state, data, msg } = res.data
          if (state === 'OK') {
            /**
             * 1000 个商品
             * 数据处理只需要36ms
             * 从接口响应到页面渲染完需要3778ms
             * 400 个商品
             * 数据处理只需要14ms
             * 从接口响应到页面渲染完需要1359ms
             * */
            // console.time('a')
            // console.time('b')
            let categoryList = []

            data[0].categoryEntityVOS.forEach((p1) => {
              categoryList.push({
                cid: p1.cid,
                name: p1.name
              })
            })
            this.categoryList = categoryList
            this.dataList = data[0].categoryEntityVOS
            this.categoryList.forEach((e, i) => {
              if (e.cid == this.currentId) {
                this.curSelectIndex = i
              }
            })
            this.$nextTick(function () {
              let nodeQuery = uni.createSelectorQuery()
              nodeQuery
                .selectAll('.product-section-header')
                .boundingClientRect((data22) => {
                  let headerNodeObj = {}
                  let topValArray = []
                  data22.forEach((p1, p2) => {
                    headerNodeObj[p2] = p1.top
                    topValArray.push(p1.top)
                  })
                  this.headerNodeObj = headerNodeObj
                  this.topValArray = topValArray
                })
                .exec()

              // console.timeEnd('a')
              uni.hideLoading()
            })
            this.shouldUpdate = false
          } else {
            uni.hideLoading()
            this.$am_toast(msg)
          }
          this.getLoading = false
        })
        .catch((err) => {
          console.log(err)
          uni.hideLoading()
          this.getLoading = false
          this.$am_toast.error('查询失败')
        })
    },
    // 跳转商品详情
    navToDetails(event) {
      let id = event.currentTarget.dataset.productId
      uni.navigateTo({
        url: `/pages/goods-details/goods-details?id=${id}`
      })
    },
    // 购买
    goBuy(event) {
      let id = event.currentTarget.dataset.pid
      let stock = event.currentTarget.dataset.stockTotal
      if (stock === 0) return
      this.$u.route('pages/place-order/submit-order', { ids: id })
    },
    asideItem(index, item) {
      this.curSelectIndex = index
      this.currentId = item.cid
      uni.pageScrollTo({
        scrollTop: this.headerNodeObj[index] - navBarHeight
      })
    }
  }
}
</script>

<style lang="scss" scoped>
$aside-wd: 168rpx;
$product-plr: 16rpx;
.navbar-slot-wrap {
  position: absolute;
  width: 174rpx;
  left: 24rpx;
}
.navbar-title-img {
  display: block;
  width: 174rpx;
  height: 37rpx;
}
.aside {
  position: fixed;
  left: 0;
  top: 44px;
  bottom: 0;
  z-index: 600;
  width: 168rpx;
  background-color: #f8fafb;
}
.aside-scroll {
  height: 100%;
}
.aside-content {
}
.aside-list {
  position: relative;
  height: 84rpx;
  padding: 0 20rpx;
  font-size: 26rpx;
  color: #666666;
  transition: all 0.3s;
  &.active {
    color: #000;
    font-weight: 600;
    background-color: #fff;
  }
  .line-active {
    width: 56rpx;
    height: 12rpx;
    position: absolute;
    bottom: 18rpx;
    &.active {
      background: linear-gradient(to right, #ec5d29 0%, #fff 100%);
    }
  }
}
.products-wrap {
  padding: 24rpx;
  padding-right: 0;
  margin-left: $aside-wd;
  background-color: #fff;
}
.product-section-header {
  padding-top: 27rpx;
  padding-left: $product-plr;
  padding-right: $product-plr;
  font-size: 28rpx;
  color: #1d2129;
}
.product-item {
  display: flex;
  padding-top: 31rpx;
  padding-left: $product-plr;
}
.product-item-retail {
  margin-top: 16rpx;
}
.product-item-cover {
  position: relative;
  overflow: hidden;
  width: 140rpx;
  height: 140rpx;
  flex-shrink: 0;
  border-radius: 15rpx;
}

.goods-card__sell-out {
  position: absolute;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(#000, 0.5);
}
.goods-card__sell-out-img {
  width: 97rpx;
  height: 45rpx;
}
.product-item-con {
  flex: 1;
  width: 0;
  padding-right: 32rpx;
  padding-bottom: 25rpx;
  margin-left: 16rpx;
  border-bottom: 1px solid #e8e8e8;
}
.product-item-name {
  font-weight: 500;
  color: #333333;
}
.product-item-con-ft {
  display: flex;
  justify-content: space-between;
  margin-top: 12rpx;
}
.product-item-price {
  font-weight: 600;
  color: #f65300;
  font-size: 34rpx;
  .price-num {
    font-size: 36rpx;
  }
}
.product-buy-btn {
  flex-shrink: 0;
  width: 140rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 30rpx;
  &.disabled {
    opacity: 0.5;
  }
}
.wx-name {
  margin-left: 50rpx;
  width: 160rpx;
  height: 54rpx;
  font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
  font-weight: 900;
  font-size: 40rpx;
  color: #1a1a1a;
  line-height: 54rpx;
  text-align: left;
  font-style: normal;
  text-transform: none;
}
.product-section-second:nth-of-type(3n + 0) {
  margin-right: 0;
}
.product-section-second {
  margin-top: 24rpx;
  margin-right: 24rpx;
  .product-section-second-img {
    width: 164rpx;
    height: 164rpx;
    border-radius: 16rpx;
  }
}
.category-name {
  margin-top: 10rpx;
  width: 164rpx;
  text-align: center;
}
</style>
